#include "../head/mainwindow.h"
#include <QApplication>
#include "../head/utils/MutiSerialControl.h"
#include "../head/utils/MutiSignalDecode.h"
#include "../head/configform.h"
#include "../head/recordform.h"
#include "../head/demoudleform.h"
#include "../head/HistoryForm.h"
#include "../head/HistoryForm_1.h"
#include "../head/HistoryForm_2.h"
#include "../head/utils/BMachineControl.h"
#include "../head/LoginForm.h"
#include "../head/RadarForm.h"
#include "../head/utils/tcpclient.h"
//#include "../head/utils/antcpserver.h"
//#include "spdlog/spdlog.h"
//#include "spdlog/async.h"
//#include "spdlog/sinks/daily_file_sink.h"
//#include "spdlog/sinks/basic_file_sink.h"
//#include "spdlog/fmt/fmt.h"
#include "../head/utils/tcpclient.h"
TcpClient client_;

HistoryForm_1 *hf_1 = NULL; //原始信号 AD采样
HistoryForm_2 *hf_2 = NULL;//星座图
DemoudleForm *df = NULL; // 信号解调
ConfigForm *cf = NULL; //系统设置
HistoryForm *hf = NULL; // 历史信号回放
RecordForm *rf;
PredictLineForm *pl;
MutiSerialControl *mutiSerialControl = NULL;
MutiSignalDecode *mutiSignalDecode = NULL;
RadarForm *radarForm;

//anTcpServer server;
#include "../head/utils/MutiConfFile.h"

//日志
//using anlogger = std::shared_ptr<spdlog::logger>;
//anlogger& getlogger() {
//    static anlogger g_anlog;
//    if (!g_anlog) {

//        QString path = QCoreApplication::applicationDirPath();
//        path+="\\logs\\anTcpServer";
//        std::string logpath=path.toStdString();
//        //std::string logpath(R"(D:\MyTest\2019_Qt\anSocket\logs\anTcpServer)");
//        logpath += ".log";

//        //是否已启动日志线程池?
//        auto tp = spdlog::thread_pool();
//        if (!tp) {
//            spdlog::init_thread_pool(65536, 1);
//        }
//        g_anlog = spdlog::daily_logger_mt<spdlog::async_factory>("anTcpServer", logpath);

//        g_anlog->set_pattern("[%Y-%m-%d %H:%M:%S.%e] [%^---%L---%$] [%t] %v");
//        g_anlog->set_level(spdlog::level::trace);
//        g_anlog->flush_on(spdlog::level::info);

//    }

//    return g_anlog;
//}
//void anMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
//{
//    //return ;

//#ifdef DEBUG
//    const char *file = context.file ? context.file : "";
//    const char *function = context.function ? context.function : "";
//#endif

//    QString data;
//    QTextStream out(&data);

//#ifdef DEBUG
//    out << msg << " [" << file << ", " << function << ", " << context.line << "]";
//#else
//    out << msg ;
//#endif

//    switch (type) {
//    case QtDebugMsg:
//        getlogger()->debug(data.toStdString());
//        //fprintf(stderr, "Debug: %s (%s:%u, %s)\n", localMsg.constData(), file, context.line, function);
//        break;
//    case QtInfoMsg:
//        getlogger()->info(data.toStdString());
//        break;
//    case QtWarningMsg:
//        getlogger()->warn(data.toStdString());
//        break;
//    case QtCriticalMsg:
//        getlogger()->critical(data.toStdString());
//        break;
//    case QtFatalMsg:
//        getlogger()->error(data.toStdString());
//        break;
//    default:
//        getlogger()->trace(data.toStdString());
//        break;
//    }

//    getlogger()->flush();
//}



void SetProcessAutoRunSelf(const QString &appPath)
{
    //注册表路径需要使用双反斜杠，如果是32位系统，要使用QSettings::Registry32Format
    QSettings settings("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run",
                       QSettings::Registry64Format);

    //以程序名称作为注册表中的键
    //根据键获取对应的值（程序路径）
    QFileInfo fInfo(appPath);
    QString name = fInfo.baseName();
    QString path = settings.value(name).toString();

    //如果注册表中的路径和当前程序路径不一样，
    //则表示没有设置自启动或自启动程序已经更换了路径
    //toNativeSeparators的意思是将"/"替换为"\"
    QString newPath = QDir::toNativeSeparators(appPath);
    if (path != newPath)
    {

        settings.setValue(name, newPath);
    }
}




int main(int argc, char *argv[])
{

    QApplication a(argc, argv);


    SetProcessAutoRunSelf(qApp->applicationFilePath());//创建程序自启注册表
    ///程序启动显示logo
    QPixmap pixmap(":/images/load.gif");
    QSplashScreen splash(pixmap);
    splash.show();
    Sleep(1000);
    splash.hide();

    QSharedMemory mem("libDemodule");//以系统exe名称为参数，定义共享内存mem
    if(!mem.create(1))//创建共享内存mem，如果该共享内存已存在，则弹出提示对话框，并退出
    {
        //QMessageBox::information(0,QObject::tr("Warning"),QObject::tr("程序已经运行！"));
        return 0;
    }

    mutiSignalDecode = new MutiSignalDecode();   
    mutiSerialControl = new MutiSerialControl();
    mutiSerialControl->init_Serial(mutiSignalDecode->DemodParam[0]->PreSignal_Len);
    BMachineControl *bm = new BMachineControl();

    qDebug()<<"bm->getCpuId()::::::::"<<bm->getCpuId();
    bm->getRegVal();

    QDateTime order_date = QDateTime::fromString("2023-11-04","yyyy-MM-dd");
    QDateTime curDateTime = QDateTime::fromString(bm->currentSettings.test_time_out,"yyyy-MM-dd");
    QDateTime test_time_out1 = curDateTime.addDays(360);
    QDateTime test_time_out2 = curDateTime.addDays(-360);
        qDebug()<<"aaaaaaaaaaaaaaaaa ";
    if(bm->currentSettings.isReged){
         qDebug()<<"bbbbbbbbbbbb ";
        MainWindow *w = new MainWindow();;
        qDebug()<<"ccccccccccccccccc ";
        w->show();
        qDebug()<<"ddddddd ";
        w->setWinTitle("电磁波解码器V2.0");
        w->setComSerial();
    }else{
        //w.setWinTitle("导向钻进管理系统DDMS【试用到期时间"+bm->currentSettings.test_time_out+"】");
        LoginForm *lf = new LoginForm;
        lf->show();
        //lf->setWindowFlags(lf->windowFlags() | Qt::WindowStaysOnTopHint);


        QString currentDate = QDateTime::currentDateTime().toString("yyyy-MM-dd");
        if(currentDate > bm->currentSettings.test_time_out || currentDate < bm->currentSettings.test_lastuse_time){
            lf->setParams(bm->getCpuId(),false);
        }else{
            lf->setParams(bm->getCpuId(),true);
        }

        lf->setWinTitle("电磁波解码器V2.0【试用到期时间"+bm->currentSettings.test_time_out+"】");

    }


    return a.exec();

}
